package com.hln.jingwushi.ui

import android.os.Bundle
import android.util.Log
import android.widget.RadioButton
import com.hln.jingwushi.MyBaseActivity
import com.hln.jingwushi.R
import com.hln.jingwushi.databinding.ActivityAirConditioningBinding
import com.hln.jingwushi.utils.Constant
import com.hln.jingwushi.utils.DataCacheUtil
import com.gdsz.libbasic.utils.assist.getCurrentDataLong
import com.gdsz.libbasic.utils.assist.getWeek
import com.gdsz.libbasic.utils.assist.getYmd
import com.gdsz.libbasic.utils.assist.weekArray
import com.gdsz.libbasic.utils.view.throttleClick
import com.zgkxzx.modbus4And.requset.ModbusReq
import com.zgkxzx.modbus4And.requset.OnRequestBack


class AirConditioningActivity : MyBaseActivity<ActivityAirConditioningBinding>() {
    var airConditionState = 0
    var airConditionMode = 0
    val airConditionTempMin = 16
    val airConditionTempMax = 31
    var airConditionTemp = 16
    var airConditionSpend = 1
    var floorHeatingState = false
    override fun ActivityAirConditioningBinding.initBinding(savedInstanceState: Bundle?) {
//        readInputRegistersClickEvent()
        initRadioGroup()
        updateAirConditioningState()
        updateFloorHeatingState()
        val currentDate = getCurrentDataLong()
        binding.tvDate.text = getYmd(currentDate)  + "   ${weekArray[getWeek(currentDate)]}"
        binding.tvName.text = DataCacheUtil.getName()
        readAirConditioningMode()
        readAirConditioningTemp()
        readAirConditioningOpenState()
        readAirConditioningSpend()
        binding.tvName.text = DataCacheUtil.getName()
        binding.tvTip.text = "方舱运行状态正常，紧急联系电话：${DataCacheUtil.getContactTel()}，紧急联系人：${DataCacheUtil.getContactPerson()}"
    }

    private fun updateAirConditioningState () {
        if (airConditionState == 1) {
            binding.ivAirConditioningState.setImageResource(R.mipmap.selector)
        } else {
            binding.ivAirConditioningState.setImageResource(R.mipmap.unselector)
        }
    }
    private fun updateAirConditioningSpend () {
        val spend = when(airConditionSpend) {
            Constant.AUTO_WIND_SPEND -> {
                "自动"
            }
            Constant.WIND_SPEND_1 -> {
                "低速"
            }
            Constant.WIND_SPEND_2 -> {
                "中速"
            }
            Constant.WIND_SPEND_3 -> {
                "高速"
            }
            else -> {
                "自动"
            }
        }
        binding.tvAirWindSpeedLab.text = "风速： $spend"
    }

    private fun updateFloorHeatingState () {
        if (floorHeatingState) {
            binding.ivFloorHeatingState.setImageResource(R.mipmap.selector)
        } else {
            binding.ivFloorHeatingState.setImageResource(R.mipmap.unselector)
        }
    }

    override fun onClick() {
        super.onClick()
        binding.ivAirConditioningState.throttleClick {
            if (airConditionState == 1) {
                writeAirConditioningOpenState(0)
            } else {
                writeAirConditioningOpenState(1)
            }

        }
        binding.ivFloorHeatingState.throttleClick {
            floorHeatingState = !floorHeatingState
            updateFloorHeatingState()
        }
//        binding.ivAirTempAdd.setOnClickListener {
//            if (airConditionTemp < airConditionTempMax) {
//                writeAirConditioningTemp(airConditionTemp + 1)
//            }
//        }
        binding.ivAirTempAdd.throttleClick {
            if (airConditionTemp < airConditionTempMax) {
                writeAirConditioningTemp(airConditionTemp + 1)
            }

        }
        binding.ivAirTempReduce.throttleClick {
            if (airConditionTemp > airConditionTempMin) {
                writeAirConditioningTemp(airConditionTemp -1)
            }

        }
        binding.ivAirWindSpeedAdd.throttleClick {
            if (airConditionSpend < Constant.WIND_SPEND_3) {

                writeAirConditioningWindSpend(airConditionSpend +1)
            }
        }
        binding.ivAirWindSpeedReduce.throttleClick {
            if (airConditionSpend > Constant.AUTO_WIND_SPEND) {
                writeAirConditioningWindSpend(airConditionSpend -1)
            }
        }
    }


    fun readAirConditioningOpenState() {
        ModbusReq.getInstance().readInputRegisters(object : OnRequestBack<ShortArray> {
            override fun onSuccess(data: ShortArray) {
                runOnUiThread {
                    airConditionState = data[0].toInt()
                    updateAirConditioningState()
                    Log.d(
                        "asd",
                        "readInputRegisters open ${data[0].toInt()} } "
                    )
                }
            }

            override fun onFailed(msg: String) {
                Log.e("asd", "readInputRegisters onFailed $msg")
            }
        }, 1, 30, 1)
    }

    fun readAirConditioningMode() {
        ModbusReq.getInstance().readInputRegisters(object : OnRequestBack<ShortArray> {
            override fun onSuccess(data: ShortArray) {
                runOnUiThread {
                    Log.d(
                        "asd",
                        "readInputRegisters mode  ${data[0].toInt()}} "
                    )
                    airConditionMode = data[0].toInt()
                    if (airConditionMode == 0) {
                        airConditionMode = 1
                    } else if (airConditionMode > 4) {
                        airConditionMode = 4
                    }
                    var radioButton =
                        (binding.radioGroup.getChildAt(airConditionMode - 1)) as RadioButton
                    radioButton.apply {
                        this.isChecked = true
                    }
                }

            }

            override fun onFailed(msg: String) {
                Log.e("asd", "readInputRegisters onFailed $msg")
            }
        }, 1, 31, 1)
    }
    fun readAirConditioningTemp() {
        ModbusReq.getInstance().readInputRegisters(object : OnRequestBack<ShortArray> {
            override fun onSuccess(data: ShortArray) {
                runOnUiThread {
                    airConditionTemp = data[0].toInt()
                    updateTemp()
                    Log.d(
                        "asd",
                        "readInputRegisters temp ${data[0].toInt()}} "
                    )
                }

            }

            override fun onFailed(msg: String) {
                Log.e("asd", "readInputRegisters onFailed $msg")
            }
        }, 1, 32, 1)
    }
    fun readAirConditioningSpend() {
        ModbusReq.getInstance().readInputRegisters(object : OnRequestBack<ShortArray> {
            override fun onSuccess(data: ShortArray) {
                runOnUiThread {
                    Log.d(
                        "asd",
                        "readInputRegisters spend ${data[0].toInt()}}} "
                    )
                    airConditionSpend = data[0].toInt()
                    updateAirConditioningSpend()
                }

            }

            override fun onFailed(msg: String) {
                Log.e("asd", "readInputRegisters onFailed $msg")
            }
        }, 1, 33, 1)
    }

    fun writeAirConditioningOpenState (state : Int) {
        ModbusReq.getInstance().writeRegisters(object : OnRequestBack<String?> {
            override fun onSuccess(t: String?) {
                runOnUiThread {
                    airConditionState = if (airConditionState == 1) {
                        0
                    } else {
                        1
                    }
                    airConditionState = state
                    updateAirConditioningState()
                }
            }

            override fun onFailed(msg: String) {

            }
        }, 1, 30, shortArrayOf(state.toShort()))
    }
    fun writeAirConditioningMode (mode : Int,modeStr : String) {
        ModbusReq.getInstance().writeRegisters(object : OnRequestBack<String?> {
            override fun onSuccess(t: String?) {
                runOnUiThread {
                    airConditionMode = mode

//                    binding.springAirModeValue.setSelection(mode -1)
                }
            }

            override fun onFailed(msg: String) {

            }
        }, 1, 31, shortArrayOf(mode.toShort()))
    }
    fun writeAirConditioningTemp (temp : Int) {
        ModbusReq.getInstance().writeRegisters(object : OnRequestBack<String?> {
            override fun onSuccess(t: String?) {
                runOnUiThread {
                    airConditionTemp = temp
                    updateTemp()
                }
            }

            override fun onFailed(msg: String) {

            }
        }, 1, 32, shortArrayOf(temp.toShort()))
    }
    fun writeAirConditioningWindSpend (spend : Int) {
        ModbusReq.getInstance().writeRegisters(object : OnRequestBack<String?> {
            override fun onSuccess(t: String?) {
                runOnUiThread {
                    airConditionSpend = spend
                    updateAirConditioningSpend()
                }
            }

            override fun onFailed(msg: String) {

            }
        }, 1, 33, shortArrayOf(spend.toShort()))
    }


    fun initSpring () {
        // 创建适配器并设置数据源
//        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, Constant.airConditionModes)
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
//        // 设置适配器
//        binding.springAirModeValue.adapter = adapter
//        // 设置选中监听器
//        binding.springAirModeValue.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
//            override fun onItemSelected(
//                parentView: AdapterView<*>?,
//                selectedItemView: View,
//                position: Int,
//                id: Long
//            ) {
//                writeAirConditioningMode(position + 1)
//                // 处理选中的选项
//            }
//
//            override fun onNothingSelected(parentView: AdapterView<*>?) {
//                // 未选中任何选项时的处理
//            }
//        }
//        binding.springAirModeValue.setSelection(airConditionMode)

    }


    fun initRadioGroup () {
        binding.radioGroup.setOnCheckedChangeListener { group, checkedId ->

            val checkedRadioButton = findViewById<RadioButton>(checkedId)
            val selectedOption = checkedRadioButton.text.toString()
            when (selectedOption) {
                "制冷" -> {
                    writeAirConditioningMode(1,"制冷")
                }
                "除湿" -> {
                    writeAirConditioningMode(2,"除湿")
                }
                "通风" -> {
                    writeAirConditioningMode(3,"通风")
                }
                "制热" -> {
                    writeAirConditioningMode(4,"制热")
                }
            }
        }
    }

    override fun notifyData(values: ShortArray) {
        runOnUiThread {
            binding.tvTemp.text = "温度  ${values[0]} ℃  湿度 ${values[1]} %"
        }
    }

    private fun updateTemp () {
        binding.tvAirTempLab.text = "温度： ${airConditionTemp} ℃"
    }

}